package cn.t.service.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Component("ossUploadService")
public class OssUploadServiceImpl implements IUploadService {

    // 通过配置注入目标路径，例如：D:/uploads/
    @Value("${file.upload-dir}")
    private String uploadDir;


    @Override
    public String upload(MultipartFile sourceFile) {
        if (sourceFile.isEmpty()) {
            log.warn("上传的文件为空");
            return null;
        }

        try {
            // 获取文件名和后缀
            String originalFilename = sourceFile.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 使用UUID生成唯一文件名
            String newFileName = UUID.randomUUID() + fileExtension;

            // 构建目标文件路径
            File destFile = new File(uploadDir + File.separator + newFileName);

            // 如果目标目录不存在，则创建
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }

            // 保存文件到本地
            sourceFile.transferTo(destFile);

            String accessUrl = String.format("http://%s:%s/upload/%s", "47.116.181.140", "8080", newFileName);

            log.info("文件保存成功，访问路径为：{}", accessUrl);
            return accessUrl;
        } catch (IOException e) {
            log.error("文件保存失败", e);
            return null;
        }
    }

}
